<template>
  <div class="app-container home">
    <!--    <div class="page-title">
          <span><i class="el-icon-office-building"></i> 工业用户总用水量监测</span>
          <el-tag type="primary">实时数据更新: {{ lastUpdateTime }}</el-tag>
        </div>-->
    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <div class="stat-card" v-if="false">
        <div class="card-title">今日用水量</div>
        <div class="value-number">{{ statistics.todayUsage }} 吨</div>
        <div>较昨日 <span :class="statistics.dayCompare >= 0 ? 'text-success' : 'text-danger'">
                    {{ statistics.dayCompare >= 0 ? '+' + statistics.dayCompare : statistics.dayCompare }}%
                </span></div>
      </div>
      <div class="stat-card">
        <div class="card-title">上月用水量</div>
        <div class="value-number">{{ statistics.lastMonthUsage }} 吨</div>
        <!--        <div>较上月 <span :class="statistics.monthCompare >= 0 ? 'text-success' : 'text-danger'">
                            {{ statistics.monthCompare >= 0 ? '+' + statistics.monthCompare : statistics.monthCompare }}%
                        </span></div>-->
      </div>
      <div class="stat-card">
        <div class="card-title">平均日用水量</div>
        <div class="value-number">{{ statistics.avgDailyUsage }} 吨</div>
        <div>近30天平均值</div>
      </div>
      <div class="stat-card">
        <div class="card-title">峰值用水量</div>
        <div class="value-number">{{ statistics.peakUsage }} 吨</div>
        <div>发生月份：{{ statistics.peakDate }}</div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-container">
      <div class="chart-info">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-card">
              <div class="info-label">平均月用水量</div>
              <div class="info-value">{{ averageMonthlyUsage }} 吨</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-card">
              <div class="info-label">最高月用水量</div>
              <div class="info-value">{{ maxMonthlyUsage }} 吨</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-card">
              <div class="info-label">最低月用水量</div>
              <div class="info-value">{{ minMonthlyUsage }} 吨</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-card">
              <div class="info-label">总用水量</div>
              <div class="info-value">{{ totalUsage }} 吨</div>
            </div>
          </el-col>
        </el-row>
        </div>
          <div class="chart-title">用水量趋势图</div>
          <div id="waterChart" style="width: 100%; height: 400px;"></div>
      </div>

    <!-- 用水量分布 -->
    <div class="chart-container">
      <div class="chart-title">月用水量分布</div>
      <div id="distributionChart" style="width: 100%; height: 400px;"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {getMonthStatistics} from "@/api/meterread/monthusage";
export default {
  name: "WaterAnalysis",
  data() {
    // 设置默认日期范围为最近30天
    const end = new Date();
    const start = new Date();
    start.setDate(start.getMonth() - 9);
    return {
      // 查询参数
      queryParams: {
        userName: '张三',
        dateRange: [this.formatMonth(start), this.formatMonth(end)]
      },
      // 统计数据
      statistics: {
        todayUsage: 0,
        dayCompare: 0,
        lastMonthUsage: 0,
        monthCompare: 0,
        avgDailyUsage: 0,
        peakUsage: 0,
        peakDate: '2025-08',
        monthMap: new Map(),
      },
      // 最后更新时间
      lastUpdateTime: this.formatTime(new Date()),
      // 图表实例
      waterChart: null,
      distributionChart: null,
      // 图表统计数据
      chartStats: {
        average: 0,
        max: 0,
        min: 0,
        total: 0
      },
    };
  },
  computed: {
    chartDataAvailable() {
      return this.chartData.dates && this.chartData.dates.length > 0;
    },
    averageMonthlyUsage() {
      return this.chartStats.average.toFixed(2);
    },
    maxMonthlyUsage() {
      return this.chartStats.max.toFixed(2);
    },
    minMonthlyUsage() {
      return this.chartStats.min.toFixed(2);
    },
    totalUsage() {
      return this.chartStats.total.toFixed(2);
    }
  },
  mounted() {
    // 延迟初始化以确保DOM完全渲染
    setTimeout(() => {
      this.initChart();
      this.loadData();
    }, 100);

    // 响应窗口大小变化，调整图表尺寸
    window.addEventListener('resize', this.resizeChart);
    // 模拟实时数据更新
    /*setInterval(() => {
      this.updateRealTimeData();
    }, 60000); // 每分钟更新一次*/
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
  },
  methods: {
    // 初始化图表
    initChart() {
      this.waterChart  = echarts.init(document.getElementById('waterChart'));
      this.distributionChart = echarts.init(document.getElementById('distributionChart'));
      // 用水量趋势图配置
      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          /*formatter: '{b}<br/>用水量: {c} 吨'*/
          formatter: function(params) {
            let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
            params.forEach(item => {
              result += `<div>
                  <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${item.color}"></span>
                  ${item.seriesName}: <span style="font-weight: bold; color: ${item.color}">${item.value} 吨</span>
                </div>`;
            });
            return result;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value',
          name: '用水量(吨)',
          min: 0,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0',
              type: 'dashed'
            }
          }
        },
        series: [{
          name: '月用水量',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#409EFF'
          },
          lineStyle: {
            width: 3,
            color: '#409EFF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.6)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          },
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          },
          markLine: {
            data: [
              { type: 'average', name: '平均值' }
            ]
          },
          data: []
        }]
      };

      // 用水量分布图配置
      const distributionOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            return `${params[0].axisValue}<br/>月份数量: ${params[0].value}个`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1-5000吨', '5000-10000吨', '10000-15000吨', '15000-20000吨', '20000吨以上'],
          axisLabel: {
            interval: 0,
            rotate: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '月份数量'
        },
        series: [{
          name: '月份数量',
          type: 'bar',
          barWidth: '60%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          label: {
            show: true,
            position: 'top'
          },
          data: [5, 12, 8, 4, 1]
        }]
      };

      this.waterChart.setOption(option);
      this.distributionChart.setOption(distributionOption);
    },

    // 加载数据
    loadData() {
      const dates = [];
      const values = [];
      getMonthStatistics().then(response => {
        this.statistics = response.data;
        const mMap = new Map(Object.entries(this.statistics.monthMap));
        // 遍历Map
        for (let key of mMap.keys()) {
          dates.push(key);
          values.push(mMap.get(key));
        }
        // 计算统计数据
        this.chartStats = this.calculateStats(values);
        // 更新图表
        this.waterChart.setOption({
          xAxis: {
            data: dates
          },
          series: [{
            data: values
          }]
        });
        // 更新分布图
        this.updateDistributionChart(values);
      });
    },
    // 计算统计数据
    calculateStats(values) {
      if (!values || values.length === 0) {
        return { average: 0, max: 0, min: 0, total: 0 };
      }

      const sum = values.reduce((a, b) => a + b, 0);
      const max = Math.max(...values);
      const min = Math.min(...values);
      const average = sum / values.length;

      return {
        average,
        max,
        min,
        total: sum
      };
    },
    // 更新分布图
    updateDistributionChart(values) {
      const ranges = [0, 0, 0, 0, 0]; // 0-5, 5-10, 10-15, 15-20, 20+

      values.forEach(value => {
        if (value > 0 && value <= 5000) ranges[0]++;
        else if (value > 5000 && value <= 10000) ranges[1]++;
        else if (value > 10000 && value <= 15000) ranges[2]++;
        else if (value > 15000 && value <= 20000) ranges[3]++;
        else if (value > 20000) ranges[4]++;
      });

      this.distributionChart.setOption({
        series: [{
          data: ranges
        }]
      });
    },
    // 处理日期范围变化
    handleDateRangeChange() {
      this.updateChartData();
    },
    // 刷新图表
    refreshChart() {
      this.loadData();
    },

    // 更新图表数据
    updateChart(chartData) {
      this.chart.setOption({
        xAxis: {
          data: chartData.dates
        },
        series: [{
          data: chartData.values
        }]
      });
    },

    // 模拟实时数据更新
    updateRealTimeData() {
      // 模拟实时数据 - 只更新最近几个数据点
      const option = this.waterChart.getOption();
      const currentData = option.series[0].data;

      // 更新最后几个数据点，模拟实时变化
      for (let i = currentData.length - 5; i < currentData.length; i++) {
        if (i >= 0) {
          // 添加随机波动
          const change = (Math.random() - 0.5) * 0.1; // -5% 到 +5%
          currentData[i] = parseFloat((currentData[i] * (1 + change)).toFixed(0));
          currentData[i] = 0;
        }
      }

      // 更新今日用水量
      // this.statistics.todayUsage = currentData[currentData.length - 1];
      this.statistics.todayUsage = 0;
      // 重新设置图表数据
      this.waterChart.setOption({
        series: [{
          data: currentData
        }]
      });
      // 更新时间
      this.lastUpdateTime = this.formatTime(new Date());
    },

    // 调整图表尺寸
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },

    // 处理查询
    handleQuery() {
      this.loadData();
    },
    // 格式化日期为YYYY-MM
    formatMonth(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      return `${year}-${month}`;
    },
    // 格式化日期为YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 格式化时间为HH:MM:SS
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    }
  }
};
</script>
<style scoped>
.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.filter-card {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}
.statistics-cards {
  display: flex;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}
.stat-card {
  flex: 1;
  min-width: 230px;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}
.chart-container {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 500px;
  margin-bottom: 20px;
}
.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}
.el-form-item {
  margin-bottom: 15px;
}
.value-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin: 10px 0;
}
.card-title {
  color: #666;
  font-size: 14px;
}
.text-success {
  color: #67c23a;
}
.text-danger {
  color: #f56c6c;
}
.card-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #409EFF;
}
.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.filter-item {
  flex: 1;
  min-width: 280px;
}
.chart-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.chart-controls {
  display: flex;
  gap: 10px;
}

.chart-info {
  margin-bottom: 20px;
}

.info-card {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  text-align: center;
  border-left: 4px solid #67C23A;
}

.info-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.info-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.chart-loading, .chart-no-data {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400px;
  color: #999;
  font-size: 14px;
}

.chart-loading i, .chart-no-data i {
  font-size: 48px;
  margin-bottom: 10px;
}

.value-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin: 10px 0;
}

.card-title {
  color: #666;
  font-size: 14px;
}
@media (max-width: 768px) {
  .stat-card {
    min-width: 100%;
  }
  .filter-item {
    min-width: 100%;
  }
}
</style>


